<template>
  <div class="grading-page-container">
    <!-- 顶部：考试信息 -->
    <div class="exam-info">
      <el-card>
        <div class="exam-info__item">
          <span>试卷名称：</span>
          <span>{{ currentQuestion.examName }}</span>
        </div>
        <div class="exam-info__item">
          <span>考试描述：</span>
          <span>{{ currentQuestion.examDescription }}</span>
        </div>
        <div class="exam-info__item">
          <span>考试时间：</span>
          <span>{{ currentQuestion.startTime }}</span>
        </div>
        <div class="exam-info__item">
          <span>剩余未批改题数：</span>
          <span style="font-size: 16px;color: rgb(250, 102, 70)">{{ currentQuestion.correctNum }}</span>/{{currentQuestion.totalNum}}
        </div>
      </el-card>
    </div>

    <!-- 当前题目 -->
    <div v-if="currentQuestion" class="question-card">
      <el-card>
        <div class="question-header">
          <span class="question-title">题目 ID：{{ currentQuestion.questionId }}</span>
          <span class="question-score">满分：{{ currentQuestion.maxScore }}分</span>
        </div>
        <div class="question-content">
          <div class="question-text">
            <span>题目内容：</span>
            <p>{{ currentQuestion.questionContent }}</p>
          </div>
          <div class="student-answer">
            <span>学生答案：</span>
            <p v-html="currentQuestion.userAnswer||'未作答'"></p>
          </div>
          <div class="correct-answer">
            <span>正确答案：</span>
            <p>{{ currentQuestion.questionAnswer }}</p>
          </div>
          <div class="question-analysis">
            <span>题目解析：</span>
            <p>{{ currentQuestion.explanation }}</p>
          </div>

        </div>
        <div class="question-grading">
          <span>得分：</span>
          <div class="score-pagination">
            <el-button
                :icon="ArrowLeftBold"
                :disabled="currentPage === 1"
                @click="prevPage"
                class="pagination-btn el-button__default"
            />
            <div class="score-buttons">
              <el-button
                  v-for="score in paginatedScores"
                  :key="score"
                  class="el-button__default"
                  :class="{'el-button__plain':userScore === score}"
                  @click="setScore(score)"
              >
                {{ score }}
              </el-button>
            </div>
            <el-button
                :icon="ArrowRightBold"
                :disabled="currentPage * 10 >= currentQuestion.maxScore + 1"
                @click="nextPage"
                class="pagination-btn el-button__default"
            />
          </div>
        </div>
      </el-card>
    </div>

    <!-- 提交按钮 -->
    <div class="submit-button">
      <el-button type="primary"   class="el-button__plain" @click="outCorrect">
        退出批改
      </el-button>
      <el-button type="primary"  @click="submitGrading" class="el-button__primary">
        提交分数
      </el-button>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, computed, defineEmits, toRefs} from "vue";
import {ArrowLeftBold, ArrowRightBold} from "@element-plus/icons-vue";
import {correctStore} from "@/stores/exam/correctStore.js";
import {ElMessage} from "element-plus";
import {getQuestionById} from "@/api/question/question.js";
import {getQuestionInfo, submitExamQuestionScore} from "@/api/question/exam.js";
const emit = defineEmits(['outCorrect'])
// 模拟的考试信息
const userScore=ref(null)
const store=correctStore()


// 当前题目数据
const currentQuestion = ref({});
const props = defineProps({
  //子组件接收父组件传递过来的值
  examId: 0,
})

const {examId} =toRefs(props)

const outCorrect=()=>{
  emit("outCorrect")
}

// 当前页码
const currentPage = ref(1);

// 得分选项（分页）
const paginatedScores = computed(() => {
  if (!currentQuestion.value) return [];
  const start = (currentPage.value - 1) * 10;
  const end = Math.min(currentPage.value * 10, currentQuestion.value.maxScore);
  return Array.from({ length: end - start + 1 }, (_, i) => start + i); // 注意这里的 +1
});

// 初始化页面
onMounted(async () => {
  try {
    // 加载第一道题目
    const res  = await getQuestionInfo(examId.value);
    currentQuestion.value =res.data ;
  } catch (error) {
    ElMessage.error("无法加载考试信息，请稍后重试！");
  }
});

// 设置得分
const setScore = (num) => {
  userScore.value = num;
};

// 上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};

// 下一页
const nextPage = () => {
  if (currentPage.value * 10 < currentQuestion.value.maxScore + 1) {
    currentPage.value++;
  }
};

// 提交批改
const submitGrading = async () => {
  try {
    // 检查当前题目是否已评分
    if (userScore.value=== null) {
      ElMessage.warning("请为当前题目选择得分！");
      return;
    }

    // // 模拟提交当前题目分数
     console.log(`提交题目 ID ${currentQuestion.value.questionId} 分数：`, currentQuestion.value.score);
      const res1=await submitExamQuestionScore(currentQuestion.value.examId,currentQuestion.value.userId,currentQuestion.value.questionId,userScore.value)
      if (res1.data===false){
        ElMessage.error("提交失败，请稍后重试！");
      }else {
        currentPage.value = 1; // 重置分页
        const res = await getQuestionInfo(examId.value);
        userScore.value=null
        if (res.data === null || res.data.correctNum === null || res.data.correctNum === 0) {
          currentQuestion.value={}
          ElMessage.success("试卷批改完毕，辛苦了~");
        }else {
           currentQuestion.value = res.data;
        }
      }
  } catch (error) {
    ElMessage.error("提交失败，请稍后重试！");
  }
};
</script>

<style scoped>
.grading-page-container {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.exam-info {
  margin-bottom: 20px;
}

.exam-info__item {
  margin: 10px 0;
  font-size: 14px;
}

.question-card {
  margin-bottom: 20px;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
  color: rgb(46, 92, 246);
}

.question-content {
  font-size: 14px;
  margin-bottom: 10px;

  .question-text,
  .correct-answer,
  .question-analysis,
  .student-answer {
    margin: 5px 0;
  }
}

.question-grading {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.score-pagination {
  display: flex;
  align-items: center;
  gap: 10px;
}

.score-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.pagination-btn {
  padding: 8px;
}

.submit-button {
  display: flex;
  justify-content: flex-end; /* 提交按钮靠右 */
  margin-top: 20px;
}
</style>